<template>
  <div>
    <el-tree
      ref="refTree"
      :data="data"
      show-checkbox
      check-strictly
      default-expand-all
      node-key="id"
      :props="{label: 'name'}"
    />
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="$emit('close')">取消</el-button>
        <el-button size="small" type="primary" @click="onSubmit">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { arrTotree } from '@/utils'
import { assignPerm, getRoleDetail } from '@/api/setting'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      data: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    async onSubmit() {
      await assignPerm({ id: this.roleId, permIds: this.$refs.refTree.getCheckedKeys() })
      this.$message.success('保存成功')
      this.$emit('close')
    },
    // 获取角色现有的权限
    async loadRoleDetail() {
      // 根据roleId获取当前这个角色已经具备的权限
      const { data: res } = await getRoleDetail(this.roleId)
      console.log(res)
      // 回填
      this.$refs.refTree.setCheckedKeys(res.permIds)
    },
    // 获取权限列表
    async loadPermissionList() {
      const { data: res } = await getPermissionList()
      // console.log(res)
      this.data = arrTotree(res)
    }
  }
}
</script>

<style>

</style>
